//
//  JCustomerAddressController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/4.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JCustomerAddressController.h"
#import "AddressPickerView.h"

#define textFeildAction 10

@interface JCustomerAddressController ()<AddressPickerViewDelegate>

@property (nonatomic , strong) JAddressAddModel *addModel;
@property (nonatomic ,strong) AddressPickerView * pickerView;

@property (nonatomic, strong) UITextField *customerName;
@property (nonatomic, strong) UITextField *customerPhone;
@property (nonatomic, strong) YYLabel *customerCity;
@property (nonatomic, strong) UITextField *customerAddress;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, copy) NSArray *areasArr;

@end

@implementation JCustomerAddressController

- (JAddressAddModel *)addModel
{
    if (!_addModel) {
        _addModel = [JAddressAddModel new];
    }
    return _addModel;
}

- (AddressPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[AddressPickerView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame)) dataArr:_areasArr];
        _pickerView.delegate = self;
        // 关闭默认支持打开上次的结果
        //        _pickerView.isAutoOpenLast = NO;
        _pickerView.hidden = YES;
    }
    return _pickerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    self.titleLabel.text = @"编辑收货地址";
    self.leftButton.hidden = NO;
    self.rightButton.hidden = YES;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.contentView.backgroundColor = kRGBColor(245, 245, 245);
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    _areasArr = [NSArray array];
    
    [self loadAddressCityRequest];
    
    [self setBgView];
    
}

- (void)setBgView
{
    NSArray *nameArr = @[@"收货人:",@"手机号:",@"省市区:",@"详细地址:"];
    
    CGRect rect = CGRectMake(0, 15 , kWindowW, 50);
    [self setViewRect:rect title:nameArr[0] num:1];
    
    CGRect rect1 = CGRectMake(0, 15 + (50), kWindowW, 50);
    [self setViewRect:rect1 title:nameArr[1] num:2];
    
    CGRect rect2 = CGRectMake(0, 15 + 2 * (50), kWindowW, 50);
    [self setViewRect:rect2 title:nameArr[2] ];
    
    
    CGRect rect3 = CGRectMake(0, 15 + 3 * (50), kWindowW, 50);
    [self setViewRect:rect3 title:nameArr[3] num:4];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, CGRectGetHeight(self.contentView.frame) - 50, kWindowW, 50);
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    saveBtn.backgroundColor = [UIColor redColor];
    [saveBtn addTarget:self action:@selector(savebtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:saveBtn];
}

- (void )setViewRect:(CGRect)rect title:(NSString *)title num:(NSInteger)num
{
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.opaque = NO;
    view.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:view];
    
    YYLabel *name = [YYLabel new];
    name.left = 15;
    name.top = 0;
    name.size = CGSizeMake(75, view.height);
    name.text = title;
    name.font = kFONT_TITLE(16);
    name.textColor = kRGBColor(106, 106, 106);
    name.textAlignment = NSTextAlignmentRight;
    [view addSubview:name];
    
    UITextField *textF = [[UITextField alloc]initWithFrame:CGRectMake(name.right + 5, 0, kWindowW - name.right - 20, view.height)];
    textF.font = kFONT_TITLE(16);
    [textF addTarget:self action:@selector(cancelHUD) forControlEvents:UIControlEventEditingDidBegin];
    [view addSubview:textF];
    if (num == 1) {
        _customerName = textF;
        if (_addressmodel.FirstName.length > 0) {
            _customerName.text = _addressmodel.FirstName;
        }
    }
    if (num == 2) {
        _customerPhone = textF;
        if (_addressmodel.PhoneNumber.length > 0) {
            _customerPhone.text = _addressmodel.PhoneNumber;
        }
    }
    if (num == 4) {
        _customerAddress = textF;
        if (_addressmodel.Address1.length > 0) {
            _customerAddress.text = _addressmodel.Address1;
        }
    }
    CALayer *line = [CALayer layer];
    line.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line.frame = CGRectMake(0, view.height - 1, kWindowW, 1);
    [view.layer addSublayer:line];
    
}

- (void)cancelHUD
{
    [SVProgressHUD dismiss];
}

- (void )setViewRect:(CGRect)rect title:(NSString *)title
{
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.opaque = NO;
    view.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:view];
    
    YYLabel *name = [YYLabel new];
    name.left = 15;
    name.top = 0;
    name.size = CGSizeMake(75, view.height);
    name.text = title;
    name.font = kFONT_TITLE(16);
    name.textColor = kRGBColor(106, 106, 106);
    name.textAlignment = NSTextAlignmentRight;
    [view addSubview:name];
    
    YYLabel *actionLabel = [YYLabel new];
    actionLabel.left = name.right + 5;
    actionLabel.top = 0;
    actionLabel.size = CGSizeMake(kWindowW - name.right - 20, view.height);
    actionLabel.font = kFONT_TITLE(16);
    
    [view addSubview:actionLabel];
    _customerCity = actionLabel;
    
    if (_addressmodel.ShortAddress.length > 0) {
        _customerCity.text = _addressmodel.ShortAddress;
    }
    
    actionLabel.textTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [self.view endEditing:YES];
        [self textEditingAction];
    };
    
    CALayer *line = [CALayer layer];
    line.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line.frame = CGRectMake(0, view.height - 1, kWindowW, 1);
    [view.layer addSublayer:line];
    
}

#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick{

    [self.pickerView setHidden:YES];
}
- (void)sureBtnClickReturnProvince:(JAddressProvinceModel *)province City:(JAddressCityModel *)city Area:(JAddressAreasModel *)area{
    if (city != nil) {
        self.customerCity.text = [NSString stringWithFormat:@"%@  %@",province.name,city.name];
        if (area != nil) {
            self.customerCity.text = [NSString stringWithFormat:@"%@  %@  %@",province.name,city.name,area.name];
        }
    }
    else
    {
        self.customerCity.text = [NSString stringWithFormat:@"%@",province.name];
    }
    
    
    self.addModel.StateProvinceId = [province.Id integerValue];
    self.addModel.CityId = [city.Id integerValue];
    self.addModel.CountyId = [area.Id integerValue];
    self.addModel.Id = 0;
    self.addModel.CustomerId = [GLOBALDATA userInfoModel].CustomerId;
    
    [self.pickerView setHidden:YES];

}

- (void)textEditingAction {
    [self.pickerView setHidden:NO];

}

- (void)savebtnClick:(UIButton *)btn
{
    // 判断有无空值 有返回
    if (![self submitBtnClick]) {
        return;
    }
    
    // 无空值
    self.addModel.FirstName = _customerName.text;
    self.addModel.Address1 = _customerAddress.text;
    self.addModel.PhoneNumber = _customerPhone.text;
    
    if (self.addressmodel.PhoneNumber.length > 0) {
        // 编辑收货地址
        self.addModel.Id = self.addressmodel.Id;
        [self addAddressRequest];
    }
    else
    {
        // 添加收货地址
        [self addAddressRequest];
    }
    
}

- (BOOL)submitBtnClick {
    if (_customerName.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入收货人"];
        return NO;
    }
    if (_customerPhone.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return NO;
    }
    if (_customerCity.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择省市区"];
        return NO;
    }
    if (_customerAddress.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细地址"];
        return NO;
    }
    if (![self validateBandCard:_customerPhone.text regularString:REG_PHONENUM_STR]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return NO;
    }
    return YES;
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setAddressmodel:(JAddressModel *)addressmodel
{
    _addressmodel = addressmodel;
    _customerName.text = _addressmodel.FirstName;
    _customerPhone.text = _addressmodel.PhoneNumber;
    _customerCity.text = _addressmodel.ShortAddress;
    _customerAddress.text = _addressmodel.Address1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

/// 获取省市区
- (void)loadAddressCityRequest
{
    NSString *url = @"Address/GetAreaJsonData";
    [JNetManager AddressCityInfoRequestUrl:url
                                   success:^(id response) {
                                       if (response) {
                                           _areasArr = response;
                                           [self.contentView addSubview:self.pickerView];
                                           
                                           
                                       }
                                   } failure:^(NSString *err) {
                                       [SVProgressHUD showErrorWithStatus:err];
                                   }];
    
}

/// 添加收货地址
- (void)addAddressRequest {
    NSString *url = @"Address/CreateAddress";
    [JNetManager AddCustomerAddressRequestUrl:url
                              addAddressModel:self.addModel
                                      success:^(id response) {
                                          if ([response integerValue] == 1) {
                                              
                                              [[NSNotificationCenter defaultCenter] postNotificationName:NSStringFromClass([JCustomerAddressController class]) object:nil userInfo:nil];
                                              
                                              [self.navigationController popViewControllerAnimated:YES];
                                          }
                                          
                                      } failure:^(NSString *err) {
                                          [SVProgressHUD showErrorWithStatus:err];
                                      }];
    
}

//- (void)editAddressRequest
//{
//    
//}

/// 正则
- (BOOL)validateBandCard:(NSString *)baneCard regularString:(NSString *)regularString
{
    BOOL flag;
    if (baneCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSPredicate *bandCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularString];
    flag = [bandCardPredicate evaluateWithObject:baneCard];
    return flag;
}

@end
